local util = require "util"
local conf = require "conf"
local require = require
local setmetatable = setmetatable
local error = error
local table = table
local ngx = ngx
local string = string
local math = math
local tonumber = tonumber
local tostring = tostring
local os = os
local user = require "user"
package.cpath = "/usr/nginx/?.so;;"
local json = require 'cjson'
module(...)

_VERSION = '0.1'
_APPID = 'wx39526549f946efe5'
_SECRET = '4a61d3fbc0837899d5b665d6388a8b00'

function default(args)
    if not args.code then
        ngx.print(json.encode({
            err = 1,
            msg = '参数不正确'
        }))
        ngx.exit(200)
    end

    local db = conf.get_mysql()
    local res = {}
    local http = require "http"

    local ok, code, _, _, body  = http:request {
        url = "https://api.weixin.qq.com/sns/jscode2session?appid=" .. _APPID .. "&secret=" .. _SECRET .. "&js_code=" .. args.code .. "&grant_type=authorization_code",
        timeout = 6000,
        method = "GET",
    }
    ngx.log(ngx.ERR, json.encode(body))
    body = json.decode(body)
    if body.errcode then
        ngx.print(json.encode({
            err = 1,
            msg = body.errmsg
        }))
        ngx.exit(200)
    else
        local openId = body.openid
        local token = ""
        local session_key = body.session_key
        local adminUser = conf.userDetail({["id"]= 1})
        local res = user.search(adminUser, {["username"] = openid})
        if res and res[1] then
            token = conf.get_token(res[1].id, 0)
        else
            res = user.create(adminUser, {["username"] = openid, ["pass"] = openid, ["role_id"] = 5})
            local insert_id = res.insert_id
            if insert_id < 1 then
                res = db:query("SELECT LAST_INSERT_ID() AS insert_id")
                if res and res[1] and res[1].insert_id then
                    insert_id = res[1].insert_id
                end
            end
            token = conf.get_token(insert_id, 0)
        end
        ngx.print(json.encode({
            err = 0,
            token = token
        }))
        ngx.exit(200)
    end
end

local class_mt = {
    __newindex = function (table, key, val)
        error('attempt to write to undeclared variable "' .. key .. '"')
    end
}
setmetatable(_M, class_mt)